#!/usr/bin/env python
# encoding: utf-8
"""
@author: guihehans
@file: CrowdSSO.py
@time: 2020/4/29 17:21
@function:

"""

import sys
import crowd
from jenkins_tool.common import const
from jenkins_tool.log.Logger import Logger

global logger
logger = Logger(clevel=const.Logging_command_level, Flevel=const.Logging_file_level)


class CrowdClient(object):

    def __init__(self):
        self.app_url = const.CROWD_SERVER
        self.app_user = const.CROWD_USER
        self.app_pass = const.CROWD_PASSWORD
        self.isConnecting = False
        self.isAuthenticated = False
        self.token = None

        self.usernameMap = {}
        self.passwordMap = {}
        self.cs = None

    # Create the reusable Crowd object
    def connect(self):
        try:
            if self.isConnecting is False:

                logger.info("CrowdSSO", sys._getframe().f_code.co_name,
                            "Connecting Crowd Server: %s/ with %s / %s" % (
                                self.app_url, self.app_user, self.app_pass)
                            , "CrowdSSO ready to connect"
                            )
                self.cs = crowd.CrowdServer(self.app_url, self.app_user, self.app_pass)
                self.isConnecting = True
                logger.info("CrowdSSO", sys._getframe().f_code.co_name, "Connection established",
                            "CrowdSSO connect server success.")
                return self.isConnecting
            else:
                return self.isConnecting

        except Exception as e:
            logger.info("CrowdSSO", sys._getframe().f_code.co_name,
                        "Failed Connecting Crowd Server: http://%s/ with %s / %s" % (
                            self.app_url, self.app_user, self.app_pass)
                        , "Failed to connect Crowd server"
                        )

            return self.isConnecting

    def login(self, username, password):
        if (self.connect()):
            # Create a session. The important bit is the token.
            logger.info("CrowdSSO", sys._getframe().f_code.co_name,
                        "User:{} trying to get authentication from crowd server".format(username)
                        , " CrowdSSO authentication success"
                        )
            session = self.cs.get_session(username, password)

            if session is not None:
                logger.info("CrowdSSO", sys._getframe().f_code.co_name,
                            "User {} authentication success, the token is {}".format(username, session['token'])
                            , " CrowdSSO authentication success"
                            )
                self.token = session['token']
                self.usernameMap[self.token] = username;
                self.passwordMap[self.token] = password;
                self.isAuthenticated = True
                return self.token
            else:
                logger.info("CrowdSSO", sys._getframe().f_code.co_name,
                            "User {} authentication failed !".format(username)
                            , "Failed to connect Crowd server"
                            )
                self.isAuthenticated = False
                return None

    def get_login_info(self, token):
        # 取得登录信息
        info = self.cs.validate_session(token)
        user_name = self.usernameMap[token]
        pass_word = self.passwordMap[token]
        return user_name, pass_word


if __name__ == '__main__':
    username = "guihe"
    password = "woshiguihe"
    cc = CrowdClient()
    token = cc.login(username, password)
    print(token)
    # token="ZbVE88VR9NRezJNYGRG72Q00"
    print(cc.get_login_info(token))
